package com.love.web.session.filter;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisStore implements Store{
	
	private JedisPool jedisPool;
	
	public RedisStore(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	public Session getSession(String sessionId) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			byte[] bytes = jedis.get(sessionId.getBytes());
			if(bytes == null){
				return null;
			}
			Session session = (Session) new StandardSerializeUtil().unserialize(bytes);
			return session;
		} catch (Exception e) {
			e.printStackTrace();
			if(jedis != null){
				jedisPool.returnBrokenResource(jedis);
			}
			throw new SessionException(e.getMessage(), e);
		} finally{
			if(jedis != null){
				jedisPool.returnResource(jedis);
				jedis = null;
			}
		}
	}

	public boolean deleteSession(String sessionId) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			long count = jedis.del(sessionId);
			if(count > 0){
				return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			if(jedis != null){
				jedisPool.returnBrokenResource(jedis);
			}
			throw new SessionException(e.getMessage(), e);
		} finally{
			if(jedis != null){
				jedisPool.returnResource(jedis);
				jedis = null;
			}
		}
	}

	public boolean setSession(String sessionId, Session session, int expireSeconds) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.setex(sessionId.getBytes(), expireSeconds, new StandardSerializeUtil().serialize(session));
		} catch (Exception e) {
			if(jedis != null){
				jedisPool.returnBrokenResource(jedis);
			}
			throw new SessionException(e.getMessage(), e);
		} finally{
			if(jedis != null){
				jedisPool.returnResource(jedis);
				jedis = null;
			}
		}
		return true;
	}

	public boolean setSession(String sessionId, Session session) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.set(sessionId.getBytes(), new StandardSerializeUtil().serialize(session));
		} catch (Exception e) {
			if(jedis != null){
				jedisPool.returnBrokenResource(jedis);
			}
			throw new SessionException(e.getMessage(), e);
		} finally{
			if(jedis != null){
				jedisPool.returnResource(jedis);
				jedis = null;
			}
		}
		return true;
	}

	public boolean expireSession(String sessionId, int expireSeconds) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.expire(sessionId.getBytes(), expireSeconds);
		} catch (Exception e) {
			if(jedis != null){
				jedisPool.returnBrokenResource(jedis);
			}
			throw new SessionException(e.getMessage(), e);
		} finally{
			if(jedis != null){
				jedisPool.returnResource(jedis);
				jedis = null;
			}
		}
		return true;
	}
	
	

}
